<?php
/**
 * Created by PhpStorm.
 * User: 69568
 * Date: 2018/2/5
 * Time: 21:53
 */

namespace App;


use App\Models\SmsCode;

class Helper
{

    /**检查是否为手机号
     * @param string $phone
     * @return bool
     */
    public static function isMobile(string $phone)
    {
        if (preg_match("/^1[34578]{1}\d{9}$/", $phone)) {
            return true;
        } else {
            return false;
        }
    }

    /** 检查验证码是否正确
     * @param $phone
     * @param $code
     * @return bool
     */
    public static function checkSmsCode($phone, $code)
    {
        $smsCode = SmsCode::wherePhone($phone)->where('code', $code)->where('status', false)->first();
        if ($smsCode) {
            $smsCode->status = true;
            $smsCode->save();
            return true;
        } else {
            return false;
        }
    }

    public static function createCode($user_id) {
        static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
        $num = $user_id;
        $code = '';
        while ( $num > 0) {
            $mod = $num % 35;
            $num = ($num - $mod) / 35;
            $code = $source_string[$mod].$code;
        }
        if(empty($code[3]))
            $code = str_pad($code,4,'0',STR_PAD_LEFT);
        return $code;
    }

    public static function decode($code) {
        static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
        if (strrpos($code, '0') !== false)
            $code = substr($code, strrpos($code, '0')+1);
        $len = strlen($code);
        $code = strrev($code);
        $num = 0;
        for ($i=0; $i < $len; $i++) {
            $num += strpos($source_string, $code[$i]) * pow(35, $i);
        }
        return $num;
    }

}